package com.bw.user_module.register;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.room.Room;

import com.blankj.utilcode.util.SPUtils;
import com.bw.base_application_sdk.BaseApplication;
import com.bw.common.entity.SaveEntity;
import com.bw.common.field.EventBusEntity;
import com.bw.common.mvvm.viewmodel.BaseViewModel;
import com.bw.common.utils.ToastShowUtils;
import com.bw.network_sdk.BaseEntity;
import com.bw.user_module.dao.UserDatabase;
import com.bw.user_module.login.LoginViewModel;
import com.bw.user_module.user.UserEntity;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class RegisterViewModel extends BaseViewModel<RegisterRepository> {

    public ObservableField<String>phone=new ObservableField<>();
    public ObservableField<String>timeStr=new ObservableField<>("获取验证码");
    public ObservableField<String>verify = new ObservableField<>("123456");
    public ObservableField<String>pwd = new ObservableField<>();
    public ObservableField<String>confirmpwd = new ObservableField<>();
    private TimeHandler timeHandler = new TimeHandler(this);
    private Thread thread;
    private int time = 10;

    public void verify(){
        if (!timeStr.get().equals("获取验证码")){
            ToastShowUtils.showShort("获取中请稍后");
            return;
        }
        time = 10;
        thread =  new Thread(){

            @Override
            public void run() {
                super.run();
                while (!interrupted()){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    timeHandler.sendEmptyMessage(0);
                }
            }
        };
        thread.start();
    }

    public void confirm(){
        if (TextUtils.isEmpty(phone.get())){
            ToastShowUtils.showShort("请输入手机号");
            return;
        }
        if (TextUtils.isEmpty(verify.get())){
            ToastShowUtils.showShort("请输入验证码");
            return;
        }
        if (TextUtils.isEmpty(pwd.get())){
            ToastShowUtils.showShort("请输入密码");
            return;
        }
        if (TextUtils.isEmpty(confirmpwd.get())){
            ToastShowUtils.showShort("请输入确认密码");
            return;
        }
        if (!pwd.get().equals(confirmpwd.get())){
            ToastShowUtils.showShort("密码不匹配，请重新输入");
            return;
        }
        //构建本次请求参数
        Map<String,Object>map=new HashMap<>();
        map.put("mobile",phone.get());
        map.put("pwd",pwd.get());
        map.put("verifyCode",verify.get());
        respository.requestRegister(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

    @Override
    public void onResult(BaseEntity entity) {
        if (entity instanceof UserEntity){
            //获取登录接口返回的userentity
            UserEntity userEntity = (UserEntity) entity;
            SPUtils.getInstance().put("userid",userEntity.data.id);
            UserDatabase db = Room.databaseBuilder(BaseApplication.getInstance(),
                    UserDatabase.class, "user.db").build();
            respository.saveUser(userEntity,db)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(RegisterViewModel.this);
        }else if (entity instanceof SaveEntity){
            EventBusEntity eventBusEntity1 = new EventBusEntity();
            eventBusEntity1.action = "refresh";
            EventBus.getDefault().post(eventBusEntity1);
            finishPage();
            EventBusEntity eventBusEntity = new EventBusEntity();
            eventBusEntity.action = "finish";
            EventBus.getDefault().post(eventBusEntity);
        }
    }

    @Override
    protected void initData() {

    }


    public static class TimeHandler extends Handler{
        private WeakReference<RegisterViewModel>weakReference;
        public TimeHandler(RegisterViewModel viewModel){
            weakReference = new WeakReference<>(viewModel);
        }
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (weakReference.get() == null)
                return;
            weakReference.get().time-=1;
            if (weakReference.get().time<=0){
                weakReference.get().timeStr.set("获取验证码");
                weakReference.get().thread.interrupt();
                return;
            }
            weakReference.get().timeStr.set(weakReference.get().time+"s");
        }
    }

}
